package com.bolingcavalry.crm.customer.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.base.ResponseResult;
import com.bolingcavalry.crm.customer.mapper.CustomerCompaniesMapper;
import com.bolingcavalry.crm.customer.service.CustomerCompaniesService;
import com.dto.CustomerCompaniesDTO;
import com.entity.customer.CustomerCompanies;
import com.vo.CustomerCompaniesVO;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;

@Service
public class CustomerCompaniesServiceImpl implements CustomerCompaniesService {
    @Autowired
    private CustomerCompaniesMapper customerCompaniesMapper;
    @Override
    public ResponseResult add(CustomerCompaniesDTO customerCompaniesDTO) {
        CustomerCompanies customerCompanies = new CustomerCompanies();
        //判断是否为空字符串
        if(StringUtils.isBlank(customerCompaniesDTO.getCompanyName())){
            return ResponseResult.error("公司名称不能为空");
        }
        //根据名称判断是否已存在
        LambdaQueryWrapper<CustomerCompanies> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(CustomerCompanies::getCompanyName, customerCompaniesDTO.getCompanyName());
        if(customerCompaniesMapper.selectOne(queryWrapper)!=null){
            return ResponseResult.success("公司名称已存在");
        }

        BeanUtils.copyProperties(customerCompaniesDTO, customerCompanies);
        customerCompanies.setCreateTime(LocalDateTime.now());
        try {
            customerCompaniesMapper.insert(customerCompanies);
        } catch (Exception e) {
            return ResponseResult.error("新增失败");
        }
        return ResponseResult.success("新增成功");
    }

    @Override
    public CustomerCompaniesVO get(Long id) {
        CustomerCompanies customerCompanies = customerCompaniesMapper.selectById(id);
        CustomerCompaniesVO customerCompaniesVO = new CustomerCompaniesVO();
        BeanUtils.copyProperties(customerCompanies, customerCompaniesVO);
        return customerCompaniesVO;
    }

    @Transactional
    @Override
    public ResponseResult batchDelete(List<Long> ids) {
            //判断要删除的客户是否存在于售后表after_sales、问题表service_problem中
            if(customerCompaniesMapper.isExistInAfterSales(ids)>0){
               return ResponseResult.error("客户存在于售后表中，请先删除售后表中的数据");
            }
            if(customerCompaniesMapper.isExistInServiceProblem(ids)>0){
                return ResponseResult.error("客户存在于问题表中，请先删除问题表中的数据");
            }
            customerCompaniesMapper.deleteBatchIds(ids);
            return ResponseResult.success("删除成功");
    }

    @Override
    public boolean update(CustomerCompaniesDTO customerCompaniesDTO) {
        CustomerCompanies customerCompanies = new CustomerCompanies();
        BeanUtils.copyProperties(customerCompaniesDTO, customerCompanies);
        customerCompanies.setUpdateTime(LocalDateTime.now());
            int i = customerCompaniesMapper.updateById(customerCompanies);
            if(i==0)
                return false;

        return true;
    }


    @Override
    public Page<CustomerCompaniesVO> getByConditions(String keyword, String companyName, String address, Integer pageNum, Integer pageSize) {
        LambdaQueryWrapper<CustomerCompanies> wrapper = new LambdaQueryWrapper<>();

        // 模糊匹配关键字
        if (StringUtils.isNotBlank(keyword)) {
            wrapper.like(CustomerCompanies::getCompanyName, keyword)
                    .or()
                    .like(CustomerCompanies::getAddress, keyword);
        }

        // 模糊匹配公司名称
        if (StringUtils.isNotBlank(companyName)) {
            wrapper.like(CustomerCompanies::getCompanyName, companyName);
        }

        // 模糊匹配公司地址
        if (StringUtils.isNotBlank(address)) {
            wrapper.like(CustomerCompanies::getAddress, address);
        }

        //先根据更新时间排序再根据创建时间排序
        wrapper.orderByDesc(CustomerCompanies::getUpdateTime, CustomerCompanies::getCreateTime);

        // 查询数据库并转换为 VO
        IPage<CustomerCompanies> iPage;
        if (pageSize == null) {
            // 查询全部数据，使用足够大的页面大小
            Page<CustomerCompanies> page = new Page<>(1, 100000);
            iPage = customerCompaniesMapper.selectPage(page, wrapper);

            // 调整分页信息，使其更符合"查询全部"的语义
            iPage.setPages(1);
            iPage.setCurrent(1);
            iPage.setSize(iPage.getTotal());
        } else {
            // 正常分页查询
            Page<CustomerCompanies> page = new Page<>(pageNum, pageSize);
            iPage = customerCompaniesMapper.selectPage(page, wrapper);
        }

        // 转换为 VO 页面对象
        Page<CustomerCompaniesVO> voPage = new Page<>();
        List<CustomerCompaniesVO> voList = iPage.convert(this::convertToVO).getRecords();

        voPage.setTotal(iPage.getTotal());
        voPage.setRecords(voList);
        voPage.setCurrent(iPage.getCurrent());
        voPage.setSize(iPage.getSize());
        voPage.setPages(iPage.getPages());

        return voPage;
    }

    // 简单的转换方法，实际可用 BeanUtils 或 MapStruct 替代
    private CustomerCompaniesVO convertToVO(CustomerCompanies entity) {
        CustomerCompaniesVO vo = new CustomerCompaniesVO();
        BeanUtils.copyProperties(entity, vo);
        return vo;
    }

}
